<!-- 翻牌形式 -->
<template>
  <n-layout class="card__container" has-sider>
    <n-layout-sider content-style="padding: 24px;">
      <n-table striped bordered size="small" :single-column="true" v-if="props.extractObject.gameMode === 'Elimi'">
        <thead>
          <tr>
            <th style="text-align: center;">主场战队</th>
            <th style="text-align: center;">客场战队</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in teamGameInfo">
            <td style="text-align: center;">{{ item.leftTeam }}</td>
            <td style="text-align: center;">{{ item.rightTeam }}</td>
          </tr>
        </tbody>
      </n-table>
      <template v-if="props.extractObject.gameMode === 'Group'">
        <div v-for="(_, index) in props.extractObject.options.groupNumber" :key="index">
          <n-divider title-placement="left">
            第{{ index + 1 }}组
          </n-divider>
          <n-tag style="margin-right: 1rem;margin-top: 1rem;" type="error" v-for="(team, i) in (groupTeam[index] ?? [])"
            :key="i">
            {{ team }}
          </n-tag>
        </div>
      </template>
    </n-layout-sider>
    <n-layout-content>
      <p class="extract__label">
        <n-gradient-text type="info" :size="24">
          {{ props.extractObject?.options?.extractLabel || '未设置抽取标题' }}
        </n-gradient-text>
      </p>
      <div class="extract__container">
        <n-tag class="left__team team" size="large" :style="leftTeamStyle" @transitionend="onLeftTeamTransitionEnd"
          :bordered="false" type="error">
          {{ cacheStore[0] }}
        </n-tag>
        <n-tag class="right__team team" size="large" :style="rightTeamStyle" @transitionend="onRightTeamTransitionEnd"
          :bordered="false" type="info">
          {{ cacheStore[1] }}
        </n-tag>
        <img class="extract__box" src="@/assets/images/box.png" @click="startAnimation">
        <p class="extract__left--team">剩余队伍：{{ teamList.length }}个</p>
      </div>
    </n-layout-content>
  </n-layout>
  <preNextButton v-if="!readOnly" revokeWarningText="一经撤回，现在抽取的结果将全部作废，您确定撤回到第三步吗？" :nowProcess="props.nowProcess"
    @preClick="preClick" @importExcel="handleImport"></preNextButton>
</template>

<script setup lang='ts'>
import { shuffleArrayInPlace } from './hooks'
import { useDialog, useMessage } from 'naive-ui';

// 接口开始
interface GameInfo {
  leftTeam: string
  rightTeam: string
}
// 接口结束
const emits = defineEmits(['preClick','finishPick']);
const props = defineProps({
  nowProcess: {
    type: Number,
    required: true
  },
  extractObject: {
    type: Object,
    required: true
  },
  readOnly: {
    type: Boolean,
    required: true
  }
});

const message = useMessage();
const dialog = useDialog();
// 新增：动画锁定状态
const isAnimating = ref(false);
const teamList = reactive<string[]>([]);
const cacheStore = reactive<string[]>([]); //存储抽出的队伍
const teamGameInfo = reactive<GameInfo[]>([]);//对战图
const groupTeam = reactive<string[][]>([]);
const groupIndex = ref(0);
const extractEvery = ref(0);//每组多少个

const init = () => {
  groupIndex.value = 0;
  const data = props?.extractObject?.data as string[] ?? [];
  const refreshData = shuffleArrayInPlace(data);
  refreshData.forEach((element: string) => {
    teamList.push(element);
  });
  extractEvery.value = Math.ceil(props.extractObject.options.extractNumber / props.extractObject.options.groupNumber) ?? 1;
}
// 控制 left__team 和 right__team 的样式
const leftTeamStyle = reactive({
  transition: "",
  top: "50%",
  left: "50%",
  opacity: "0",
  transform: "translate(-50%, -50%)",
});

const rightTeamStyle = reactive({
  transition: "",
  top: "50%",
  left: "50%",
  opacity: "0",
  transform: "translate(-50%, -50%)",
});


const startAnimation = () => {
  if (isAnimating.value) return;
  if (teamList.length === 0) return message.error('已经抽光了！'); // 没有队伍可抽时停止
  isAnimating.value = true;
  const resultTeam = teamList.pop() as string;
  cacheStore.push(resultTeam);

  // 使用nextTick确保DOM更新后再执行动画
  nextTick(() => {
    if (cacheStore.length === 1) {
      Object.assign(leftTeamStyle, {
        transition: "all 1s ease-in-out",
        top: "10%",
        left: "30%",
        opacity: "1",
      });
    } else if (cacheStore.length === 2) {
      Object.assign(rightTeamStyle, {
        transition: "all 1s ease-in-out",
        top: "10%",
        left: "70%",
        opacity: "1",
      });
    }
  });
};

// 优化后的移出动画
const moveOutAnimation = () => {
  // 强制重绘确保动画触发
  void leftTeamStyle.transform;
  void rightTeamStyle.transform;

  Object.assign(leftTeamStyle, {
    transition: "all 1s ease-in-out",
    left: "-100%",
  });

  Object.assign(rightTeamStyle, {
    transition: "all 1s ease-in-out",
    left: "150%",
  });

  // 动画完成后重置状态
  setTimeout(() => {
    resetAnimation();
    prepareNextRound();
    isAnimating.value = false; // 解锁动画
  }, 1000);
};

// 重置动画状态
const resetAnimation = () => {
  Object.assign(leftTeamStyle, {
    transition: "none",
    top: "50%",
    left: "50%",
    opacity: "0",
  });

  Object.assign(rightTeamStyle, {
    transition: "none",
    top: "50%",
    left: "50%",
    opacity: "0",
  });

  // 强制重绘
  nextTick(() => {
    leftTeamStyle.transition = "";
    rightTeamStyle.transition = "";
  });
};

// 准备下一轮
const prepareNextRound = () => {
  if (props.extractObject.gameMode === 'Elimi') {
    teamGameInfo.push({
      leftTeam: cacheStore[0],
      rightTeam: cacheStore[1]
    });
  } else if (props.extractObject.gameMode === 'Group') {
    cacheStore.forEach((team: string) => {
      if (groupIndex.value === 0) {
        groupTeam.push([]);
      }
      if (groupTeam[groupIndex.value].length === extractEvery.value) {
        groupTeam.push([])
        groupIndex.value++;
      }
      groupTeam[groupIndex.value].push(team);
    })
  } else {
    console.log('@@@');
  }
  cacheStore.length = 0; // 清空缓存
};

// 修改过渡结束事件处理
const onLeftTeamTransitionEnd = () => {
  if (cacheStore.length === 1) {
    if (props.extractObject.options.gameMode === 'Elimi') {
      isAnimating.value = false; // 第一段动画完成，解锁
    }

    if (props.extractObject.options.gameMode === 'Group') {
      moveOutAnimation(); // 第二段动画
    }
  } else if (cacheStore.length === 2 && leftTeamStyle.left === "30%") {
    moveOutAnimation(); // 第二段动画
  }
};

const onRightTeamTransitionEnd = () => {
  if (cacheStore.length === 2 && rightTeamStyle.left === "70%") {
    moveOutAnimation();
  }
};

init();
const preClick = () => {
  emits('preClick', 'lastInfo');
}

// 导出样式表
const handleImport = () => {
  if (teamList.length !== 0) return message.error('尚有队伍未抽完，无法导出');
  dialog.warning({
    title: '警告',
    content: '您确定导出excel抽签结果吗？一旦导出，不可返回到上一步骤！',
    positiveText: '确定',
    negativeText: '不确定',
    draggable: true,
    onPositiveClick: () => {
      emits('finishPick',teamGameInfo,groupTeam);
    },
  })
}
</script>
<style scoped lang='scss'>
.card__container {
  background: #fff;
  border-radius: 12px;

  .extract__info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 1rem;
    margin: 1rem 0;
  }

  .n-layout-sider {
    background: #fff;
    border-right: 1px solid #e7e7e7;
  }

  .extract__label {
    text-align: center;
    margin: 0.5rem 0;
  }

  .extract__container {
    height: 400px;
    position: relative;

    .extract__box {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      cursor: pointer;
      width: 120px;
      /* 调整大小 */
      transition: all 0.3s ease;
      filter: drop-shadow(0 0 5px rgba(0, 0, 0, 0.1));

      &:hover {
        transform: translate(-50%, -50%) scale(1.05);
      }
    }

    .extract__left--team {
      position: absolute;
      left: 50%;
      top: 70%;
      transform: translate(-50%, -50%);
      cursor: pointer;
      color: #4090EF;
      font-size: 1.1rem;
      font-weight: bold;
    }

    .team {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      opacity: 0;
    }
  }
}
</style>